import {useAsyncData, type UseFetchOptions} from "#app";
import {defu} from "defu";
import {useUserStore} from "~/stores/user-store";
import {uuid} from 'lsp-uuid'
import {ResponseResult} from "~~/server/resources/types/response-result";
import {RESULT_CODE_ERROR_COMMON} from "~~/server/resources/constants/constant";

const useEventFetch = async <T>(url: string, options: UseFetchOptions<object> = {}, methodType: "POST" | "PUT" | "DELETE" | "GET") => {
    const userStore = useUserStore();
    const headers = {Authenticate: userStore.getAuthenticate};
    const defaults: UseFetchOptions<object> = {
        headers: headers,
        method: methodType,
    };
    const option = defu(options, defaults);
    const key = uuid();
    const requestUrl = "/api/" + useRuntimeConfig().public.serverMethod + url;
    const {data} = await useAsyncData(key, () => useCsrfFetch(requestUrl, option));
    const result = data.value?.data?.value as ResponseResult<T>
    if (result) {
        return result;
    }
    return new ResponseResult(RESULT_CODE_ERROR_COMMON, null, '');
}

export const usePostEventFetch = async <T>(url: string, options: UseFetchOptions<object> = {}) => {
    return await useEventFetch<T>(url, options, "POST")
}
export const useGetEventFetch = async <T>(url: string, options: UseFetchOptions<object> = {}) => {
    return await useEventFetch<T>(url, options, "GET")
}
export const usePutEventFetch = async <T>(url: string, options: UseFetchOptions<object> = {}) => {
    return await useEventFetch<T>(url, options, "PUT")
}
export const useDeleteEventFetch = async <T>(url: string, options: UseFetchOptions<object> = {}) => {
    return await useEventFetch<T>(url, options, "DELETE")
}

